﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SimpleOrmCFPC.Core.Model;
using SimpleOrmCFPC.Helpers;

namespace SimpleOrmCFPC.Core.Dao.Helpers
{
    public class CreateEntityRequestFactory
    {
        public string ComputeRequest<T>()
        {
            IEnumerable<string> names = from property in typeof(T).GetProperties() select property.HasAttribute<ManyToOneAttribute>() ? property.Name + "Id" : property.Name;
            return string.Format("insert into {0} ({1}) values ({2})", typeof (T).GetEntityName(),
                                 string.Join(",", names.ToArray()),
                                 string.Join(",", (from c in names select "?").ToArray()));
        }

        public IEnumerable<object> ComputeValues<T>(T obj)
        {
            var properties = typeof (T).GetProperties();
            return properties.Select(property => ComputeValue(property, obj)).ToList();
        }


        private object ComputeValue<T>(PropertyInfo property, T obj)
        {
            object computeValue = property.GetValue(obj, new object[0]);
            if (property.GetCustomAttributes(typeof (PrimaryKeyAttribute), true).Length > 0 && (int) computeValue == 0)
            {
                return null;
            }
            if (property.HasAttribute<ManyToOneAttribute>())
            {
               computeValue = property.PropertyType.GetPrimaryKey().GetValue(computeValue, new object[0]);
            }
            return computeValue;
        }
    }
}